package com.pearadmin.nucleus.aspect;

import com.pearadmin.common.annotation.Log;
import com.pearadmin.system.domain.SysOperLog;
import com.pearadmin.system.service.ISysOperLogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.StringTokenizer;

@Aspect
@Component
public class LogAspect {

    @Resource
    private ISysOperLogService sysOperLogService;

    // 配置织入点
    @Pointcut("@annotation(com.pearadmin.common.annotation.Log)")
    public void logPointCut()
    {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
    {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e)
    {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult)
    {
        try {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }

            String title = controllerLog.title();

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            String userName =  SecurityUtils.getSubject().getPrincipal().toString();
            String host = SecurityUtils.getSubject().getSession().getHost();
            SysOperLog sysOperLog = new SysOperLog();

            String agent = request.getHeader("User-Agent");

            StringTokenizer st = new StringTokenizer(agent,";");

            String brower = st.nextToken();
            String os = st.nextToken();

            if(host.equals("0:0:0:0:0:0:0:1")){
                host = "127.0.0.1";
            }

            sysOperLog.setOperator(userName);
            sysOperLog.setIp(host);
            sysOperLog.setCreateTime(new Date());
            sysOperLog.setBrower(brower);
            sysOperLog.setLocation(os);
            sysOperLog.setTitle(title);
            sysOperLog.setBusinessType(controllerLog.businessType().toString());
            if (e != null)
            {
                sysOperLog.setStatus("500");
                sysOperLog.setErrorMsg(e.getMessage());
            }else{
                sysOperLog.setStatus("200");
                sysOperLog.setErrorMsg("暂无错误信息");
            }
            saveOperLog(sysOperLog);

        }catch (Exception exp){
             exp.printStackTrace();
        }
    }

    @Async
    public void saveOperLog(SysOperLog sysOperLog){
        sysOperLogService.save(sysOperLog);
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(Log.class);
        }
        return null;
    }

}
